import { AppRouteRecord } from "@/types/router";
import { router } from "@/router";
import { setWorktab } from "@/utils/navigation/worktab";
import { useWorktabStore } from "@/store/modules/worktab";
import { useRoute } from "vue-router";

// 打开外部链接
export const openExternalLink = (link: string) => {
  window.open(link, "_blank");
};

/**
 * 菜单跳转（增强版 - 基于 art-design-pro 理念）
 * @param item 菜单项
 * @param jumpToFirst 是否跳转到第一个子菜单
 * @returns
 */
export const handleMenuJump = (
  item: AppRouteRecord,
  jumpToFirst: boolean = false,
) => {
  console.log(`[Navigation] 🎯 菜单跳转: ${item.meta.title} (${item.path})`);

  // 处理外部链接
  const { link, isIframe } = item.meta;
  if (link && !isIframe) {
    console.log(`[Navigation] 🔗 打开外部链接: ${link}`);
    return openExternalLink(link);
  }

  let targetPath = item.path;
  let targetRoute = item;

  // 如果需要跳转到第一个子菜单
  if (jumpToFirst && item.children?.length) {
    // 递归查找第一个可见的叶子节点菜单
    const findFirstLeafMenu = (items: AppRouteRecord[]): AppRouteRecord => {
      for (const child of items) {
        if (!child.meta.isHide) {
          return child.children?.length
            ? findFirstLeafMenu(child.children)
            : child;
        }
      }
      return items[0];
    };

    const firstChild = findFirstLeafMenu(item.children);
    
    // 如果第一个子菜单是外部链接则打开新窗口
    if (firstChild.meta?.link) {
      console.log(`[Navigation] 🔗 打开子菜单外部链接: ${firstChild.meta.link}`);
      return openExternalLink(firstChild.meta.link);
    }

    targetPath = firstChild.path;
    targetRoute = firstChild;
  }

  // 🎯 核心优化：检测重复路由跳转并直接处理 worktab
  const currentPath = router.currentRoute.value.path;
  const worktabStore = useWorktabStore();
  
  console.log(`[Navigation] 📍 当前路径: ${currentPath}, 目标路径: ${targetPath}`);

  if (currentPath === targetPath) {
    console.log(`[Navigation] 🔄 检测到重复点击，直接激活 worktab 和缓存`);
    
    // 直接处理 worktab 状态，模拟路由变化的效果
    const mockRoute = {
      path: targetPath,
      name: targetRoute.name,
      meta: targetRoute.meta,
      params: router.currentRoute.value.params,
      query: router.currentRoute.value.query,
      matched: router.currentRoute.value.matched
    };

    // 🔧 关键修复：直接调用 setWorktab 确保标签页正确激活
    if (!targetRoute.meta.isHideTab) {
      console.log(`[Navigation] 📋 直接激活工作标签页: ${targetRoute.meta.title}`);
      setWorktab(mockRoute as any);
    }

    // 🎯 强制触发组件刷新机制
    triggerComponentRefresh(targetPath);
    
    return Promise.resolve(); // 返回 resolved promise 保持接口一致性
  }

  // 正常路由跳转
  console.log(`[Navigation] ➡️ 执行正常路由跳转: ${targetPath}`);
  return router.push(targetPath);
};

/**
 * 触发组件刷新机制
 * @param path 目标路径
 */
const triggerComponentRefresh = (path: string) => {
  console.log(`[Navigation] 🔄 触发组件刷新: ${path}`);
  
  // 方法1: 触发自定义事件，通知组件刷新数据
  window.dispatchEvent(new CustomEvent('menu-refresh', { 
    detail: { path } 
  }));
  
  // 方法2: 通过 worktab store 的缓存管理机制
  const worktabStore = useWorktabStore();
  const currentTab = worktabStore.getTab(path);
  
  if (currentTab?.name) {
    // 临时添加到排除列表再移除，强制重新激活缓存
    console.log(`[Navigation] 🔄 重新激活组件缓存: ${currentTab.name}`);
    worktabStore.addKeepAliveExclude(currentTab);
    
    // 使用 nextTick 确保排除生效后再移除
    setTimeout(() => {
      worktabStore.removeKeepAliveExclude(currentTab.name!);
    }, 10);
  }
};
